package com.spit.hkpost.ui.frg

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.spit.hkpost.R
import com.spit.hkpost.api.UIHelper
import com.spit.hkpost.base.BaseFragment
import com.spit.hkpost.bean.DataBean
import com.spit.hkpost.bean.RfidStateBean
import com.spit.hkpost.bean.db.RfidBean
import com.spit.hkpost.databinding.FRfidParentBinding
import com.spit.hkpost.ext.ZKING_ADD_TYPE
import com.spit.hkpost.ext.bindViewPager2
import com.spit.hkpost.ext.init
import com.spit.hkpost.ext.showToast
import com.spit.hkpost.mar.eventViewModel
import com.spit.hkpost.ui.newfrg.RfidAllFrg
import com.spit.hkpost.ui.newfrg.RfidMatchFrg
import com.spit.hkpost.util.MusicUtils
import com.spit.hkpost.util.VoiceUtils
import com.spit.hkpost.viewmodel.RfidModel
import com.spit.hkpost.viewmodel.RfidParentModel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.nav
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.random.Random

/**
 * User: Nike
 *  2024/10/10 09:49
 */
class RfidParentFrg: BaseFragment<RfidParentModel, FRfidParentBinding>() {

    val rfidModel: RfidModel by activityViewModels()

    val rfidParentModel: RfidParentModel by activityViewModels()

    var fragments: ArrayList<Fragment> = arrayListOf()

    private val lock = ReentrantLock()

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()
        mViewModel.epcPrefix.set(if (!mViewModel.getConfigPrefix().isNullOrEmpty()) mViewModel.getConfigPrefix() else "NO")
        mDatabind.includeViewpager.viewpagerLinear.setBackgroundColor(ContextCompat.getColor(requireContext(), android.R.color.transparent))
        MusicUtils.init(requireActivity())
        VoiceUtils.init(requireActivity())

        setViewPage()

        mDatabind.etText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                rfidParentModel.searchText.value = p0.toString()
            }

            override fun afterTextChanged(p0: Editable?) {
            }
        })

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                rfidModel.epcData.value = null
                rfidModel.scanData.value = null
            }
        })
    }

    //region 设置viewpager
    private fun setViewPage() {
        var bundle = Bundle()
        bundle.putString("prefix", mViewModel.epcPrefix.get())

        val rfidAllFrg = RfidAllFrg()
        rfidAllFrg.arguments = bundle
        fragments.add(rfidAllFrg)

        val rfidMatchFrg = RfidMatchFrg()
        rfidMatchFrg.arguments = bundle
        fragments.add(rfidMatchFrg)

        mDatabind.includeViewpager.viewPager.init(this, fragments)
        var mTitles =
            arrayListOf(
                getString(R.string.all),
                getString(R.string.match),
            )

        mDatabind.includeViewpager.magicIndicator.bindViewPager2(
            mDatabind.includeViewpager.viewPager,
            mTitles
        )
        mDatabind.includeViewpager.viewPager.offscreenPageLimit = mTitles.size
    }
    //endregion

    inner class ProxyClick() {

        fun onConfig(){
            val dialog = ConfigBottomFrg()
            dialog.setOnItemClickListener(object : ConfigBottomFrg.OnItemClickListener{
                override fun onPrefix(prefix: String) {
                    viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
                        var allList = ArrayList<DataBean>()
                        var matchList = ArrayList<DataBean>()
                        if (prefix.isNullOrEmpty()){
                            mViewModel.epcPrefix.set("NO")
                            mViewModel.listBean.forEach{
                                it.status = 0
                                allList.add(it)
                            }
                            withContext(Dispatchers.Main) {
                                rfidParentModel.listAllBean.value = allList
                                rfidParentModel.listMatchBean.value = matchList
                                onUploadUI(false)
                            }
                            return@launch
                        }
                        mViewModel.epcPrefix.set(prefix)
                        var rfidList = ArrayList<RfidBean>()
                        mViewModel.listBean.forEach {
                            var containsPrefix = prefix!!.split(",").any { s ->
                                it.tagId!!.startsWith(s, ignoreCase = true)
                            }
                            if (containsPrefix){
                                it.status = 1
                                matchList.add(it)
                                var rfidBean = RfidBean()
                                rfidBean.epc = it.tagId!!
                                rfidBean.crearDate = it.crearDate!!
                                rfidBean.today = mViewModel.today.get()
                                rfidList.add(rfidBean)
                            }else{
                                it.status = 0
                            }
                            allList.add(it)
                        }
//                        mViewModel.rfidDao.addAll(rfidList)
                        withContext(Dispatchers.Main) {
                            rfidParentModel.listAllBean.value = allList
                            rfidParentModel.listMatchBean.value = matchList
                            val foundMatch = mViewModel.listBean.any { bean ->
                                prefix!!.split(",").any { s ->
                                    bean.tagId!!.startsWith(s, ignoreCase = true)
                                }
                            }
                            onUploadUI(foundMatch)
                        }
                    }
                }
            })
            dialog.show(childFragmentManager, "a")
        }

        fun onSearch(){
            if (mViewModel.listBean.size == 0)return
            UIHelper.startSearchRfidFrg(nav(), mDatabind.etText.text.toString(), mViewModel.listBean)
        }

        fun onZking(){
//            UIHelper.startZxingAct(ZKING_ADD_TYPE)
            viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
                mViewModel.rfidDao.deleteAll()
            }
        }

        fun onSave(){
            /* when{
                 mViewModel.listBean.size == 0 ->showToast(getString(R.string.no_data))
                 else ->{
                     mViewModel.onSave(mViewModel.listBean)
                 }
             }*/

            mViewModel.showProgress.set(true)
            val list = ArrayList<RfidStateBean>().apply {
                add(RfidStateBean(tagId = "asd12312312312123", rssi = "0"))
                add(RfidStateBean(tagId = "asd12332423312123", rssi = "0"))
//                add(RfidStateBean(tagId = "asd1231231231676575623", rssi = "0"))
//                add(RfidStateBean(tagId = "asd1231234563423", rssi = "0"))
//                add(RfidStateBean(tagId = "asd123125687567312123", rssi = "0"))
//                add(RfidStateBean(tagId = "asd12312312368967823", rssi = "0"))
//                add(RfidStateBean(tagId = "asd1231237867123", rssi = "0"))
                add(RfidStateBean(tagId = "fds51ds6f5s", rssi = "0"))
                add(RfidStateBean(tagId = "dsf2f05s 0", rssi = "0"))
                add(RfidStateBean(tagId = "asd21sa5da6", rssi = "0"))
                add(RfidStateBean(tagId = "efd56e0d", rssi = "0"))
                add(RfidStateBean(tagId = "v45fd1s5", rssi = "0"))
                add(RfidStateBean(tagId = "u56+ty1uty0u2ty", rssi = "0"))
            }
            list.shuffle(Random)

            Observable.fromIterable(list)
                .concatMap { bean ->
                    Observable.just(bean)
                        .delay(2, TimeUnit.SECONDS) // 延迟一秒
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    { bean ->
                        rfidModel.epcData.value = bean
//                        LogUtils.e(bean)
                    },
                    { error ->
                        // 处理错误
                        Log.e("MainActivity", "Error processing beans", error)
                    },
                    {
                        // 所有 bean 处理完成
                        mViewModel.showProgress.set(false)
                        LogUtils.e("MainActivity", "All beans processed")
                        runBlocking {
                            delay(2000)
                            LogUtils.e("onSave")
                            mViewModel.onSave(mViewModel.listBean)
                        }
                    }
                )

        }

        fun onClear(){
            mViewModel.listBean.clear()
            mViewModel.title.set(requireActivity().getString(R.string.text11) + " " + "( " + 0 + " )")
            onUploadUI(false)
            mDatabind.etText.setText("")
            rfidParentModel.parentOpenStatu.value = false
        }
    }

    override fun createObserver() {
        super.createObserver()
        rfidParentModel.mutableTitle.observe(viewLifecycleOwner, {
            mViewModel.title.set(requireActivity().getString(R.string.text11) + " " + "( " + it + " )")
        })
        mViewModel.isLoaddingBean.observe(viewLifecycleOwner, Observer{
            if (it.isLoading){
                showLoading(getString(R.string.text14))
            }else{
                Handler(Looper.getMainLooper()).postDelayed({
                    dismissLoading()
                }, 1000)
            }
        })

        eventViewModel.zkingType.observeInFragment(this, Observer {
            if (it.type == ZKING_ADD_TYPE){
                rfidModel.epcData.value = RfidStateBean(
                    tagId = it.text.toString(),
                    rssi = "0"
                )
            }
        })

        eventViewModel.longPressKeyCode.observeInFragment(this, Observer {
            if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
                when (it) {
                    1 -> {
                        rfidModel.isOpen.value = true
                        mViewModel.showProgress.set(true)
                    }
                    2 -> {
                        rfidModel.isOpen.value = false
                        mViewModel.showProgress.set(false)
                        when{
                            mViewModel.listBean.size == 0 -> return@Observer
                            else ->{
                                runBlocking {
                                    delay(1500)
                                    mViewModel.onSave(mViewModel.listBean)
                                }
                            }
                        }
                    }
                }
            }
        })

        rfidModel.epcData.observe(viewLifecycleOwner, {
            if (it == null) return@observe
            lock.lock()
            try {
                viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
                    var containsPrefix = false
                    if (!mViewModel.epcPrefix.get().isNullOrEmpty()){
                        containsPrefix = mViewModel.epcPrefix.get()!!.split(",").any { s ->
                            it.tagId!!.startsWith(s, ignoreCase = true)
                        }
                    }
                    val tagId = it.tagId!!
                    val predicate =  mViewModel.listBean.any{ it.tagId == tagId }
                    if (!predicate){
                        var nowString = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy/MM/dd HH:mm:ss"))
                        var bean = DataBean(
                            tagId = tagId,
                            crearDate = nowString,
                            today = mViewModel.today.get(),
                            status = if (containsPrefix) 1 else 0)
                        mViewModel.listBean.add(bean)

                        if (containsPrefix){
                            VoiceUtils.start()
//                            onSaveSQL(it.tagId, nowString)
                        }else{
                            MusicUtils.play()
                        }
                        onSaveSQL(it.tagId, nowString)
                        withContext(Dispatchers.Main) {
                            if (containsPrefix){
                                onUploadUI(true)
                            }
                            rfidParentModel.epcUploadData.value = bean
                        }
                    }
                }
            } finally {
                lock.unlock()
            }
        })
    }

    private fun onSaveSQL(tagId: String, nowString: String) {
        /*var timeBean = mViewModel.rfidDao.findById(tagId, mViewModel.today.get())
        */
        var timeBean = RfidBean()
        timeBean.epc = tagId
        timeBean.crearDate = nowString
        timeBean.today = mViewModel.today.get()
        mViewModel.rfidDao.add(timeBean)
    }

    fun onUploadUI(isUp: Boolean){
        if (isUp){
            mDatabind.layout.setBackgroundColor(ContextCompat.getColor(appContext, R.color.red_ff0000))
            mDatabind.tvPre.setTextColor(ContextCompat.getColor(appContext, R.color.white))
            mDatabind.tvEpc.setTextColor(ContextCompat.getColor(appContext, R.color.white))
        }else{
            mDatabind.layout.setBackgroundColor(ContextCompat.getColor(appContext, R.color.w_f4f9fd))
            mDatabind.tvEpc.setTextColor(ContextCompat.getColor(appContext, R.color.black_0A1629))
            mDatabind.tvPre.setTextColor(ContextCompat.getColor(appContext, R.color.black_0A1629))
        }
    }

}